﻿using System;
using Microsoft.Phone.Controls;
using System.Windows;
using Coding4Fun.MissionControl.WP.Misc;
using Coding4Fun.MissionControl.WP.ViewModels;
using Coding4Fun.Toolkit.Storage;

namespace Coding4Fun.MissionControl.WP.Views
{
    public partial class SetsPage : PhoneApplicationPage
    {
        public SetsPage()
        {
            InitializeComponent();
        }

        private async void InitializeConnection()
        {
            bool commandSent = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location, 
                Constants.COMMAND_SERVER_HELLO, string.Empty);
            if (!commandSent)
            {
                Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL);
                CommonViewModel.Instance.IsWaiting = false;
            }
        }

        private void btnTrash_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove the " + CommonViewModel.Instance.CurrentServer.Name + " service?",
                "Trash Service", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                MainPageViewModel.Instance.Servers.Remove(CommonViewModel.Instance.CurrentServer);
                Serialize.Save(Constants.SERVERS_FILE, MainPageViewModel.Instance.Servers);

                NavigationService.GoBack();
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            CommandViewModel.Instance.HandleOverlay(e);
            base.OnBackKeyPress(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Because the application is navigating back to the server list, 
            // we need to make sure that the server is marked as a new one, so that
            // any of the incoming commands are simply ignored.
            if (e.Uri.ToString().Contains("ServerList"))
            {
                CommonViewModel.Instance.CurrentServer = new Models.Server();
            }

            base.OnNavigatedFrom(e);
        }

        private void btnAddSet_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/AddSetPage.xaml", UriKind.Relative));
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            CommonViewModel.Instance.IsWaiting = true;

            InitializeConnection();
        }

        private void WaitingOverlayLayoutUpdated(object sender, EventArgs e)
        {
            if (grdConnectOverlay.Visibility == System.Windows.Visibility.Collapsed)
            {
                ApplicationBar.IsVisible = true;
            }
            else
            {
                ApplicationBar.IsVisible = false;
            }
        }
    }
}